package 集合;

import org.junit.Test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Set储存无序(先根据HashCode决定储存位置,无需遍历)、不可重复(然后按照equals()方法判断)
 * 添加新数据时按照链表添加,JDK7新元素在链表上指向原元素、JDK8新元素在数组内
 * 重写HashCode时用31的原因：1.【31=(i<<5)-1是素数】减少Hanh值的冲突,提高查找效率
 *                        2.31占用31 bits,相乘数据溢出概率较小
 */
public class SetDemo{
    @Test
    public void test() throws ParseException {
        Set<Object> set = new HashSet<>();
        set.add(123);
        set.add(123);
        TreeSet<Object> treeSet = new TreeSet<>();
//        treeSet.add(123);
//        treeSet.add(345);
//        treeSet.add(678);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        person ming = new person("ming", 25, df.parse("1996-01-27"));
        person wang = new person("wang", 55,df.parse("1985-07-27"));
        person hong = new person("hong", 63, df.parse("1999-11-21"));
        person hei = new person("hei", 47, df.parse("1990-06-17"));
        person bai = new person("bai", 18, df.parse("1968-04-07"));
        person zhangshang = new person("zhangshang", 26, df.parse("1988-09-12"));
        treeSet.add(new person("ming", 25, df.parse("1996-01-27")));
        treeSet.add(new person("wang", 55,df.parse("1985-07-27")));
        treeSet.add(new person("hong", 63, df.parse("1999-11-21")));
        treeSet.add(new person("hei", 47, df.parse("1990-06-17")));
        treeSet.add(new person("bai", 18, df.parse("1968-04-07")));
        treeSet.add(new person("zhangshang", 26, df.parse("1988-09-12")));
        System.out.println(set.size());
        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext())
        System.out.println(iterator.next());
    }

    class person implements Comparable{
        private String name;
        private int age;
        private Date date;
        public person() {
        }
        public person(String name, int age, Date date) {
            this.name = name;
            this.age = age;
            this.date = date;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public Date getDate() {
            return date;
        }
        public void setDate(Date date) {
            this.date = date;
        }
        @Override
        public int compareTo(Object o) {
            if(o instanceof person){
                person oo=(person)o;
                return this.name.compareTo(oo.name);
            }
            return 0;
        }
        @Override
        public String toString() {
            return "person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", date=" + date +
                    '}';
        }
    }
}
